package org.imsetal.ilchatservice.service;

import com.alibaba.fastjson.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.imsetal.ilchatservice.mapper.DialogueMapper;
import org.imsetal.ilchatservice.pojo.Dialogue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Condition;

@Service
public class ChatService {
    @Value("${myconfig.chat.url}")
    private String chatUrl;
    @Value("${myconfig.chat.api}")
    private String chatAPI;

    @Resource
    private WebClient.Builder webClientBuilder;

    @Resource
    DialogueMapper dialogueMapper;

    public Flux<String> getReply(Long userId,Long dialogueId, String selectModel,String userMessage){
        Dialogue dialogue=dialogueMapper.selectOne(new QueryWrapper<Dialogue>().eq("id",dialogueId));
        if(dialogue==null){
            Dialogue newDialogue=new Dialogue().addUserMessage(userMessage);
            newDialogue.setUserid(userId);
            return webClientBuilder.build()
                    .post()
                    .uri(chatUrl)
                    .header(HttpHeaders.AUTHORIZATION,"Bearer "+chatAPI)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .bodyValue(
                            "{\"model\": \""+selectModel+"\", " +
                                    "\"stream\": true, " +
                                    "\"messages\": [{\"role\": \"user\", \"content\": \""+userMessage+"\"}], " +
                                    "\"temperature\": 0.3," +
                                    "\"max_tokens\": 1500 }"
                    )
                    .retrieve()
                    .bodyToFlux(String.class)
                    .flatMap(res->{
                        System.out.println(res);
                        if(!res.equals("[DONE]")){
                            JSONObject jsonObject=JSON.parseObject(res);
                            boolean isLastOne= (boolean) jsonObject.get("lastOne");
                            if(isLastOne){
                                String content=jsonObject.getString("content");
                                System.out.println("最终消息:\n"+content);
                                newDialogue.addAssistantMessage(content);
                                dialogueMapper.insert(newDialogue);
                                System.out.println(newDialogue.getId());
                                jsonObject.put("dialogueid",newDialogue.getId());
                            }
                            return Flux.just(jsonObject.toJSONString());
                        }else{
                            return Flux.just(res);
                        }
                    });
        }else{
            dialogue.addUserMessage(userMessage);
            return webClientBuilder.build()
                    .post()
                    .uri(chatUrl)
                    .header(HttpHeaders.AUTHORIZATION,"Bearer "+chatAPI)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .bodyValue(
                            "{\"model\": \""+selectModel+"\", " +
                                    "\"stream\": true, " +
                                    "\"messages\": "+dialogue.getMessages()+", " +
                                    "\"temperature\": 0.3," +
                                    "\"max_tokens\": 1500 }"
                    )
                    .retrieve()
                    .bodyToFlux(String.class)
                    .flatMap(res->{
                        System.out.println(res);
                        if(!res.equals("[DONE]")){
                            JSONObject jsonObject=JSON.parseObject(res);
                            boolean isLastOne= (boolean) jsonObject.get("lastOne");
                            if(isLastOne){
                                String content=jsonObject.getString("content");
                                System.out.println("最终消息:\n"+content);
                                dialogue.addAssistantMessage(content);
                                dialogueMapper.updateById(dialogue);
                                System.out.println(dialogue.getId());
                                jsonObject.put("dialogueid",dialogue.getId());
                            }
                            return Flux.just(jsonObject.toJSONString());
                        }else{
                            return Flux.just(res);
                        }
                    });
        }
    }

    public Mono<List<Dialogue>> getUserAllDialogue(Long userid){
        List<Dialogue> dialogues=dialogueMapper.selectList(new QueryWrapper<Dialogue>().eq("userid", userid));
        Collections.reverse(dialogues);
        return Mono.just(dialogues);
    }
}